// ignore_for_file: file_names

import 'package:flutter/services.dart';

/// 只允许输入小数
class UsDoubleTextInputFormatter extends TextInputFormatter {
  int decimalsNum; // 保留几位小数
  static const defaultDouble = 0.001;
  static double strToFloat(String str, [double defaultValue = defaultDouble]) {
    try {
      return double.parse(str);
    } catch (e) {
      return defaultValue;
    }
  }

  UsDoubleTextInputFormatter({this.decimalsNum = -1});

  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    String value = newValue.text;
    int selectionIndex = newValue.selection.end;
    if (value == ".") {
      value = "0.";
      selectionIndex++;
    } else if (value != "" &&
        value != defaultDouble.toString() &&
        strToFloat(value, defaultDouble) == defaultDouble) {
      value = oldValue.text;
      selectionIndex = oldValue.selection.end;
    }
    if (decimalsNum != -1 && value.contains('.')) {
      String tempValue = value.split('.')[1];
      if (tempValue.length > decimalsNum) {
        value = value.substring(0, value.length - 1);
        selectionIndex = oldValue.selection.end;
      }
    }

    return TextEditingValue(
      text: value,
      selection: TextSelection.collapsed(offset: selectionIndex),
    );
  }
}
